package com.lixl.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class MulitTotalService {
	
	public int getTotal(int[] datas){
		int total = 0;
		for(int i:datas){
			total += i;
		}
		return total;
	}
	
	private AtomicInteger total1 = new AtomicInteger();
	public int getTotalByAtomicInteger(int[] datas){
		ExecutorService service = Executors.newFixedThreadPool(5);
		for(int i:datas){
			service.execute(new AtomicWorker(i));
		}
		service.shutdown();
		while(true){
			if(service.isTerminated()){
				break;
			}
		}
		return total1.get();
	}
	private class AtomicWorker implements Runnable{
		private int i;
		public AtomicWorker(int i) {
			this.i = i;
		}
		
		@Override
		public void run() {
			total1.addAndGet(i);
		}
	}
	
	private volatile Integer total2 = 0;
	public int getTotalByLock(int[] datas){
		ExecutorService service = Executors.newFixedThreadPool(5);
		for(int i:datas){
			service.execute(new AtomicWorker2(i));
		}
		service.shutdown();
		while(true){
			if(service.isTerminated()){
				break;
			}
		}
		return total2;
	}
	private class AtomicWorker2 implements Runnable{
		private int i;
		public AtomicWorker2(int i) {
			this.i = i;
		}
		
		@Override
		public void run() {
			synchronized (total2) {
				total2 += i;
			}
		}
	}
}
